import collectdata, { collectfile } from "./collectdata.mjs";
import thin_render from "./thin_render.mjs";
import validate from "./validate.mjs";

/**
 * 创建自定义对话框
 * @param {Object} options 配置选项
 * @param {string} options.template 对话框模板
 * @param {Object} options.data 对话框数据
 * @param {string} options.buttons 按钮配置，默认为"close"
 * @param {boolean} options.autoclose 是否自动关闭，默认为true
 * @param {HTMLElement} options.container 容器元素，默认为document.body
 */
export function dialog({
  template,
  data,
  buttons = "cancel",
  autoclose = true,
  container = document.body,
}) {
  let div = [];
  let _fn = {
    cancel: (res) => {
      console.log("default cancel", res);
      res?.close();
    },
  }; // 存储按钮回调函数
  let _this;
  // 返回值对象，包含close方法和动态添加的按钮方法
  let returnValue = {
    // cancel: (fn) => {
    //   _fn["cancel"] = fn;
    //   return _this;
    // },
  };

  // 解析按钮配置，为每个按钮创建处理函数
  buttons.split(/,/).forEach((button) => {
    div.push({
      button: button,
      click: async (e) => {
        console.log(e);
        let dialog = e.sender.closest("dialog");
        if (["cancel", "close"].includes(button)) {
          console.log({ button, _fn });
          if (button in _fn) {
            console.log({ button, _fn });
          }

          valid();
        } else {
          // 验证对话框内容
          validate({
            container: dialog,
            ignoreinsertrow: true,
            valid: valid,
            invalid: () => {
              e.done();
            },
          });
        }
        // 验证通过后的处理函数
        function valid() {
          let data = collectdata(dialog);
          let files = collectfile(dialog);
          console.log({ data, files });
          // 执行按钮对应的回调函数
          if (button in _fn) {
            if (autoclose) {
              // console.log({ data, files });
              if (Object.keys(files).length > 0) {
                // console.log({ data, files });
                _fn[button](data, files);
              } else {
                _fn[button](data);
              }
              container.removeChild(e.sender.closest("dialog"));
            } else {
              // console.log({ data, files });
              _fn[button]({
                data,
                files: Object.keys(files).length > 0 ? files : undefined,
                close: () => {
                  container.removeChild(e.sender.closest("dialog"));
                },
                goback: () => {
                  e.done();
                },
              });
            }
          }
        }
      },
    });

    // 为每个按钮添加回调函数设置方法
    returnValue[button] = (fn) => {
      _fn[button] = fn;
      return _this;
    };
  });

  // 渲染对话框
  function render() {
    console.log({ template, this: this });
    _this = this;
    let dialog = document.createElement("dialog");
    container.appendChild(dialog);
    dialog.showModal();
    thin_render(dialog, [template, { div }]);
    return this;
  }

  return render.call(returnValue);
}

/**
 * 创建确认对话框
 * @param {string} template 对话框模板
 * @param {Object} data 对话框数据
 * @param {HTMLElement} container 容器元素
 */
export function confirm(template, data, container = document.body) {
  let confirm, cancel, _this;

  // 渲染确认对话框
  function render() {
    // console.log({ template, this: this });
    _this = this;
    let dialog = document.createElement("dialog");
    container.appendChild(dialog);
    dialog.showModal();
    if (data) dialog.thin_data = data;

    // 渲染确认和取消按钮
    thin_render(dialog, [
      template,
      {
        div: [
          {
            button: "cancel",
            click: (e) => {
              if (cancel) cancel();
              container.removeChild(dialog);
            },
          },
          {
            button: "confirm",
            click: (e) => {
              validate({
                container: dialog,
                ignoreinsertrow: true,
                valid: () => {
                  let data = collectdata(dialog);
                  let files = collectfile(dialog);
                  if (confirm) {
                    console.log({ data, files });
                    if (Object.keys(files).length > 0) {
                      confirm(data, files);
                    } else {
                      confirm(data);
                    }
                  }
                  container.removeChild(dialog);
                },
                invalid: () => {
                  e.done();
                },
              });
            },
          },
        ],
      },
    ]);
    return this;
  }

  // 返回对象，包含confirmed和cancelled方法用于设置回调
  return render.call({
    confirmed: (fn) => {
      confirm = fn;
      return _this;
    },
    cancelled: (fn) => {
      cancel = fn;
      return _this;
    },
  });
}

/**
 * 创建提示对话框
 * @param {string} template 对话框模板
 * @param {Object} data 对话框数据
 */
export function alert(template, data) {
  let container = document.body;
  let close, _this;

  // 渲染提示对话框
  function render() {
    console.log({ template, this: this });
    _this = this;
    let dialog = document.createElement("dialog");
    container.appendChild(dialog);
    dialog.showModal();
    if (data) dialog.thin_data = data;
    dialog.onclose = close;

    // 渲染关闭按钮
    thin_render(dialog, [
      template,
      {
        div: [
          {
            button: "close",
            click: (e) => {
              if (close) close();
              container.removeChild(dialog);
            },
          },
        ],
      },
    ]);
    return this;
  }

  // 返回对象，包含close方法用于设置关闭回调
  return render.call({
    close: (fn) => {
      close = fn;
      return _this;
    },
  });
}
